package com.example.clockin.JavaUi.slice;

import com.alibaba.fastjson.JSONObject;
import com.example.clockin.ResourceTable;
import com.haibin.httpnet.HttpNetClient;
import com.haibin.httpnet.builder.Request;
import com.haibin.httpnet.builder.RequestParams;
import com.haibin.httpnet.core.Response;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Environment;
import ohos.data.resultset.ResultSet;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class setProflieAbilitysliceSlice extends AbilitySlice {
    private TableLayout imgShowLayout;
    private Text promptText;
    private Button imgEnterBtn;
    private List<Image> imgContainer;
    private List<Integer> selectIndex;
    private List<Uri> imgsUri;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_select_image_layout);

        String[] permission = {
                "ohos.permission.WRITE_MEDIA",
                "ohos.permission.READ_USER_STORAGE",
                "ohos.permission.READ_MEDIA"
        };
        requestPermissionsFromUser(permission,0);

        imgShowLayout = (TableLayout)findComponentById(ResourceTable.Id_img_show_layout);
        imgShowLayout.setColumnCount(4);
        promptText = (Text) findComponentById(ResourceTable.Id_text_prompt_info);
        imgEnterBtn = (Button) findComponentById(ResourceTable.Id_img_enter_btn);
        if(imgEnterBtn != null){
            // 设置图片选择确定事件
            imgEnterBtn.setClickedListener(component -> {
                selectIndex = new ArrayList<>();
                int i = 0;

                for (Image img : imgContainer) {
                    if (img.getAlpha() == 0.5) {
                        selectIndex.add(i);
                    }
                    i++;
                }
                if(selectIndex.size() != 1){
                    // 提示用户选择一张照片
                    new ToastDialog(getContext())
                            .setText("请选择一张图片哦！")
                            .setAlignment(LayoutAlignment.CENTER)
                            .show();
                    selectIndex = null;
                }else{
                    // 调用方法上传图片
                    new Thread(() -> {
                        DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
                        File saveFile = null;
                        try {
                            InputStream finput = helper.obtainInputStream(imgsUri.get(selectIndex.get(0)));
                            File targetDirFile = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

                            if(!targetDirFile.exists()){
                                targetDirFile.mkdirs();
                            }
                            saveFile = new File(targetDirFile, UUID.randomUUID().toString() + ".jpg");

                            FileOutputStream foutput = new FileOutputStream(saveFile);
                            byte[] readBuffer = new byte[8192];
                            int readLength = finput.read(readBuffer);
                            while (readLength > 0){
                                foutput.write(readBuffer, 0, readLength);
                                readLength = finput.read(readBuffer);
                            }
                            foutput.flush();
                            foutput.close();
                            finput.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        HttpNetClient client = new HttpNetClient();
                        File file = new File(saveFile.getAbsolutePath());

                        RequestParams fileparam = new RequestParams()
                                .putFile("files", file);

                        //请求对象
                        Request filerequest = new Request.Builder()
                                .encode("UTF-8")
                                .method("POST")
                                .params(fileparam)
                                .timeout(13000)
                                .url("http://101.37.28.215:8003/upload")
                                .build();

                        try {
                            Response response = client.newCall(filerequest).execute();
                            String body = response.getBody();
                            System.out.println("我是图片上传请求结果：" + body);
                            JSONObject responseJson1 = (JSONObject)JSONObject.parse(body);

                            if(responseJson1.getBooleanValue("success")){
                                //数据上传
                                JSONObject result = (JSONObject)responseJson1.get("result");

                                RequestParams jsonparams = new RequestParams()
//                                        .put("userId", MainAbilityListSlice.nowuserID)
                                        .put("file", result.getString("filePaths"));

                                // 添加图片路径
                                Request jsonrequest = new Request.Builder()
                                        .encode("UTF-8")
                                        .method("POST")
                                        .params(jsonparams)
                                        .timeout(13000)
                                        .url("http://101.37.28.215:8001/user/uploadprofile")
                                        .build();

                                Response jsonresponse = client.newCall(jsonrequest).execute();
                                String jsonbody = jsonresponse.getBody();
                                System.out.println("我是json数据请求结果：" + jsonbody);

                                JSONObject responseJson2 = (JSONObject)JSONObject.parse(body);

                                if(!responseJson2.getBooleanValue("success")){
                                    //提示用户上传失败
                                    new ToastDialog(getContext())
                                            .setText("上传失败，请再试一次")
                                            .setAlignment(LayoutAlignment.CENTER)
                                            .show();
                                }
                            }else {
                                //提示用户上传失败
                                new ToastDialog(getContext())
                                        .setText("上传失败，请再试一次")
                                        .setAlignment(LayoutAlignment.CENTER)
                                        .show();
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                            // 提示用户上传失败
                            new ToastDialog(getContext())
                                    .setText("上传失败，请再试一次")
                                    .setAlignment(LayoutAlignment.CENTER)
                                    .show();
                        }

                        getContext().getUITaskDispatcher().asyncDispatch(() -> {
                            // 清空组件
                            imgsUri = null;
                            selectIndex = null;
                            imgContainer = null;
                        });

                        // 跳回JS。
                        terminateAbility();
                    }).start();
                }
            });
        }
    }
    @Override
    public void onActive() {
        super.onActive();
        displayPicture();
    }

    private void displayPicture(){
        imgShowLayout.removeAllComponents();
        imgContainer = new ArrayList<>();
        imgsUri = new ArrayList<>();

        DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
        try{
            ResultSet result = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
            if (result == null) {
                promptText.setVisibility(Component.VISIBLE);
            } else {
                promptText.setVisibility(Component.HIDE);
            }
            while (result != null && result.goToNextRow()) {
                int mediaId = result.getInt(result.getColumnIndexForName(AVStorage.Images.Media.ID));
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, "" + mediaId);
                imgsUri.add(uri);
                FileDescriptor filedesc = helper.openFile(uri, "r");
                ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                decodingOpts.desiredSize = new Size(260, 260);
                ImageSource imageSource = ImageSource.create(filedesc, null);
                PixelMap pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);
                Image img = new Image(setProflieAbilitysliceSlice.this);

                img.setId(mediaId);
                img.setHeight(260);
                img.setWidth(260);
                img.setMarginsTopAndBottom(5,5);
                img.setMarginsLeftAndRight(5,5);
                img.setCornerRadius(30);
                img.setPixelMap(pixelMap);
                img.setScaleMode(Image.ScaleMode.ZOOM_CENTER);

                img.setClickedListener(component -> {
                    // 为图片设置选中效果。
                    if(img.getAlpha() == 0.5){
                        img.setAlpha(1.0f);
                    }else{
                        img.setAlpha(0.5f);
                    }
                });

                imgShowLayout.addComponent(img);
                imgContainer.add(img);
            }
        }catch(DataAbilityRemoteException | FileNotFoundException e){
            e.printStackTrace();
        }
        if (imgsUri.size() > 0){
            promptText.setVisibility(Component.HIDE);
            imgEnterBtn.setVisibility((Component.VISIBLE));
        }else{
            promptText.setVisibility(Component.VISIBLE);
            promptText.setText("No picture.");
            imgEnterBtn.setVisibility(Component.HIDE);
        }
    }
}
